<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="2">
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="roleslist" border stripe>
        <!--展开列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 栅格，一共24列-->
            <el-row :class="['bdbottom',i1 === 0 ? 'bdtop' : '','vcenter']" v-for="(item1,i1) in scope.row.children"
                    :key="item1.id">
              <!--一级权限-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(item1.id,scope.row)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--二,三级权限-->
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '' : 'bdtop','vcenter']"
                        v-for="(item2,i2) in item1.children" :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag type="success" closable
                            @close="removeRightById(item2.id,scope.row)">{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-row>
                      <el-tag type="warning" closable @close="removeRightById(item3.id,scope.row)"
                              v-for="(item3,i3) in item2.children" :key="item3.id">{{item3.authName}}
                      </el-tag>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" lable="#"/>
        <el-table-column prop="roleName" label="角色名称"/>
        <el-table-column prop="roleDesc" label="角色描述"/>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"
                       @click="showEditDialog(scope.row.id)">编辑
            </el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini"
                       @click="removeRolesById(scope.row.id)">删除
            </el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini"
                       @click="showSetRightsDialog(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页插件-->
    </el-card>
    <!--添加角色对话框-->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addDialogClosed"
    >
      <el-form :model="addRolesForm" :rules="addRolesRules" ref="addRolesRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑角色对话框-->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClosed"
    >
      <el-form :model="editRolesForm" :rules="editRolesRules" ref="editRolesRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!--分配权限对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRightsDialogClosed"
    >
      <!--树形控件-->
      <el-tree :data="rightslist" :props="treeProps" show-checkbox
               node-key="id" default-expand-all
               :default-checked-keys="defKeys"
               ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Roles",
    data() {
      return {
        roleslist: [],
        disabled: false,
        addDialogVisible: false,
        editDialogVisible: false,
        setRightsDialogVisible: false,
        addRolesForm: {
          roleName: '',
          roleDesc: ''
        },
        editRolesForm: {},
        rightslist: [],
        addRolesRules: {
          roleName: [
            {required: true, message: '请输入角色名称', trigger: 'blur'},
            {
              min: 1,
              max: 50,
              message: '长度在 1 到 10 个字符',
              trigger: 'blur'
            }
          ],
          roleDesc: [
            {required: true, message: '请输入角色描述', trigger: 'blur'},
            {
              min: 1,
              max: 50,
              message: '长度在 1 到 20 个字符',
              trigger: 'blur'
            }
          ],
        },
        editRolesRules: {
          roleName: [
            {required: true, message: '请输入角色名称', trigger: 'blur'},
            {
              min: 1,
              max: 50,
              message: '长度在 1 到 10 个字符',
              trigger: 'blur'
            }
          ],
          roleDesc: [
            {required: true, message: '请输入角色描述', trigger: 'blur'},
            {
              min: 1,
              max: 500,
              message: '长度在 1 到 20 个字符',
              trigger: 'blur'
            }
          ],
        },
        treeProps: {
          label: 'authName',
          children: 'children'
        },
        //默认选中节点的id
        defKeys: [],
        //当前角色id
        roleId: '',
      }
    },
    created() {
      this.getRolesList()
    },
    methods: {
      getRolesList() {
        this.$store.dispatch('getRolesList_').then(() => {
          this.roleslist = this.$store.state.roles_list
        })
      },
      addRoles() {
        this.$refs.addRolesRef.validate(valid => {
          if (!valid) return
          this.$store.dispatch('addRoles_', this.addRolesForm).then(() => {
            if (this.$store.state.roles_state !== 201) {
              return this.$message.error("角色添加失败")
            }
            this.addDialogVisible = false
            this.getRolesList()
            this.$message.success("角色添加成功")
          })
        })
      },
      showEditDialog(id) {
        this.$store.dispatch('getRolesById_', id).then(() => {
          if (this.$store.state.roles_state !== 200) {
            return this.$message.error("查询角色失败")
          }
          this.editRolesForm = this.$store.state.roles
        })
        this.editDialogVisible = true
      },
      removeRolesById(id) {
        this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('deleteRolesById_', id).then(() => {
            if (this.$store.state.roles_state !== 200) {
              return this.$message.error("删除失败")
            }
            this.getRolesList()
            this.$message({type: 'success', message: '删除成功!'});
          })
        }).catch(() => {
          this.$message({type: 'info', message: '已取消删除'});
        })
      },
      editRoles() {
        this.$refs.editRolesRef.validate(valid => {
          if (!valid) return
          this.$store.dispatch('updateRoles_', {id: this.editRolesForm.roleId, roles: this.editRolesForm}).then(() => {
            if (this.$store.state.roles_state !== 200) {
              return this.$message.error("角色修改失败")
            }
            this.editDialogVisible = false
            this.getRolesList()
            this.$message.success("角色修改成功")
          })
        })
      },
      //监听添加关闭
      addDialogClosed() {
        this.$refs.addRolesRef.resetFields()
      },
      editDialogClosed() {
        this.$refs.editRolesRef.resetFields()
      },
      //删除3级权限
      removeRightById(rightId, role) {
        this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let param = {"roleId": role.id, "rightId": rightId}
          this.$store.dispatch('removeRightById_', param).then(() => {
            if (this.$store.state.roles_state !== 200) {
              return this.$message.error("删除失败")
            }
            role.children = this.$store.state.roles
            this.$message({type: 'success', message: '删除成功!'});
          })
        }).catch(() => {
          this.$message({type: 'info', message: '已取消删除'});
        })
      },
      showSetRightsDialog(role) {
        this.roleId = role.id
        console.log("roleId=", this.roleId);
        this.$store.dispatch('getRightsTree_').then(() => {
          if (this.$store.state.right_state !== 200) {
            return this.$message.error("查询权限列表失败")
          }
          this.rightslist = this.$store.state.right_list
          this.getLeafKeys(role, this.defKeys)
        })
        this.setRightsDialogVisible = true
      },
      //递归获取三级权限id，存到defKeys
      getLeafKeys(node, arr) {
        //当前节点不包含children，将id加入数组
        if (!node.children) {
          return arr.push(node.id)
        }
        node.children.forEach(item => {
          this.getLeafKeys(item, arr)
        })
      },
      //监听权限对话框关闭后清空id
      setRightsDialogClosed() {
        this.defKeys = []
      },
      //分配权限
      allotRights() {
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStr = keys.join(',')
        let params = {id: this.roleId, rids: {rids: idStr}}
        this.$store.dispatch('allotRights_', params).then(() => {
          if (this.$store.state.roles_state !== 200) {
            return this.$message.error("操作失败")
          }
          this.getRolesList()
          return this.$message.success("操作成功")
        })
        this.setRightsDialogVisible = false
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
